#ifndef __MY_ONLINE_MANAGER_H__
#define __MY_ONLINE_MANAGER_H__
#include "Util.hpp"
#include <unordered_map>
#include <mutex>

class OnlineManager
{
public:
    // 进入游戏大厅/房间
    void EnterGameHall(id_t uid, ws_server_t::connection_ptr conn)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        _game_hall[uid] = conn;
    }
    void EnterGameRoom(id_t uid, ws_server_t::connection_ptr conn)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        _game_room[uid] = conn;
    }
    // 退出游戏大厅/房间
    void ExitGameHall(id_t uid)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        _game_hall.erase(uid);
    }
    void ExitGameRoom(id_t uid)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        _game_room.erase(uid);
    }
    // 判断是否在大厅/房间内
    bool IsInGameHall(id_t uid)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        return _game_hall.count(uid);
    }
    bool IsInGameRoom(id_t uid)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        return _game_room.count(uid);
    }
    // 从游戏大厅/房间获取WebSocket连接
    ws_server_t::connection_ptr GetConFromHall(id_t uid)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        auto it = _game_hall.find(uid);
        if(it == _game_hall.end())
        {
            return ws_server_t::connection_ptr();
        }
        return it->second;
    }
    ws_server_t::connection_ptr GetConFromRoom(id_t uid)
    {
        std::unique_lock<std::mutex> lockguard(_mtx);
        auto it = _game_room.find(uid);
        if(it == _game_room.end())
        {
            return ws_server_t::connection_ptr();
        }
        return it->second;
    }
private:
    std::unordered_map<id_t, ws_server_t::connection_ptr> _game_hall; // 游戏大厅
    std::unordered_map<id_t, ws_server_t::connection_ptr> _game_room; // 游戏房间
    std::mutex _mtx;
};

#endif